﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Newtonsoft.Json;

namespace BlockMain_Class
{

    /// <summary>
    /// 获取节点列表 先在缓存中获取 没有数据,同步数据库 装载缓存 
    /// </summary>
    public static class GetPeerList
    {
        public static List<string> Get()
        {
            List<string> li = new List<string>();
            //获取缓存
            var idlist = Cache.Get("peerlist");
            if (idlist == null)
            {
                //读取mongodb
                PeerList rec = new PeerList();
                MongodbHelpers<PeerList> mon = new MongodbHelpers<PeerList>();
                var val = mon.QueryAll().Select(a=>a.Id.ToString());
                Cache.Insert("peerlist", val);
                foreach (var item in val)
                {
                    li.Add(item.ToString());
                }
            }
            else
            {
                var str = idlist.ToString().Replace("{", "").Replace("}", "");
                var list = JsonConvert.DeserializeObject<List<string>>(str);
                foreach (var item in list)
                {
                    li.Add(item);
                }

            }
            return li;

        }

        /// <summary>
        /// 新增节点时更新缓存
        /// </summary>
        /// <returns></returns>
        public static void Update()
        {
            MongodbHelpers<PeerList> mon = new MongodbHelpers<PeerList>();
            var val = mon.QueryAll().Select(a=>a.Id.ToString());
            Cache.Insert("peerlist", val);
        }

    }
}
